using HalconDotNet;

namespace ocr车牌识别联合编程
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            HswcCar.MouseWheel += (sender, e) =>
            {
                HswcCar.HSmartWindowControl_MouseWheel(sender, e);
            };
            hswc2.MouseWheel += (sender, e) =>
            {
                hswc2.HSmartWindowControl_MouseWheel(sender, e);
            };
            InitializeCamera();
        }
        HImage ho_Image = null;
        // 声明全局变量
        private HWindow _hWindow; //显示窗体的引用
        private HFramegrabber _framegrabber; //相机采集器
        private bool _isGrabbing = false; //是否继续采集
        private Thread _grabThread; //声明一个实时采集图像的线程
                                    // 初始化相机
        private void InitializeCamera()
        {
            try
            {
                // 打开相机（参数需根据相机类型调整）
                _framegrabber = new HFramegrabber("GigEVision2", 0, 0, 0, 0, 0, 0, "default",
                                                  -1, "default", -1, "false", "default",
                                                  "default", 0, -1);

                // 获取 HSmartWindowControl 的 Halcon 窗口句柄
                _hWindow = hswc2.HalconWindow;
            }
            catch (HalconException ex)
            {
                //MessageBox.Show($"相机初始化失败: {ex.Message}");
            }
        }
        // 开始实时采集
        private void StartGrabbing()
        {
            if (_framegrabber == null) InitializeCamera();

            _isGrabbing = true;
            //定义线程，在线程方法进行图像循环采集
            _grabThread = new Thread(GrabLoop);
            _grabThread.IsBackground = true;
            _grabThread.Start();
        }
        // 采集循环（在独立线程中运行）
        private void GrabLoop()
        {
            while (_isGrabbing)
            {
                try
                {
                    // 抓取图像
                    ho_Image = _framegrabber.GrabImageAsync(-1);

                    // 在 Halcon 窗口中显示图像
                    _hWindow.DispObj(ho_Image);
                    hswc2.SetFullImagePart();
                    ho_Image.Dispose();
                }
                catch (HalconException ex)
                {
                    // 处理异常（如相机断开）
                    if (ex.GetErrorCode() == 5302) // 采集超时
                        Thread.Sleep(1000);
                    else
                        break;
                }
            }
        }
        // 停止采集
        private void StopGrabbing()
        {
            _isGrabbing = false;
            _grabThread?.Join(); // 等待线程结束
            _framegrabber?.Dispose();
            _framegrabber = null;
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            //OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.Filter = "图片文件|*.png;*.jpg;*.jpeg;*.bmp";
            //openFileDialog.Title = "请选择图片";
            //if (openFileDialog.ShowDialog() == DialogResult.OK)
            //{
            //    ho_Image = new HImage(openFileDialog.FileName);

            //    HswcCar.HalconWindow.DispObj(ho_Image);
            //    //支持缩放
            //    HswcCar.SetFullImagePart();
            //}
            //OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.Filter = "所有图片|*.bmp;*.jpg";
            //openFileDialog.Title = "加载图片";
            //openFileDialog.RestoreDirectory = true;
            //if (openFileDialog.ShowDialog() == DialogResult.OK)
            //{
            //    image = new HImage(openFileDialog.FileName);
            //    this.hswcCar.HalconWindow.DispObj(image);
            //    this.hswcCar.SetFullImagePart();
            //}

            StartGrabbing();
        }

        private void button2_Click(object sender, EventArgs e)
        {
          
            //以图片中点为旋转点进行旋转 获取旋转角度
            HOperatorSet.TextLineOrientation(ho_Image, ho_Image, 50, -0.872665, 0.872665, out HTuple angle);
            double phi = angle;
            HImage ImageRotate = ho_Image.RotateImage(-phi / 3.14 * 180, "constant");
            //增强对比度
            HImage ImageEmphasize = ImageRotate.Emphasize(7, 7, 1);
            //中值滤波去椒盐噪声
            HImage ImageMedian = ImageEmphasize.MedianImage("circle", 5, "mirrored");
            //获取三个通道
            HImage redImage = ImageEmphasize.Decompose3(out HImage greenImage, out HImage blueImage);
            HImage hImage = redImage.TransFromRgb(greenImage, blueImage, out HImage sImage, out HImage vImage, "hsv");
            //二值化
            HRegion region = sImage.BinaryThreshold("max_separability", "light", out HTuple UsedThreshold);
            //开运算
            HRegion RegionOpening = region.OpeningCircle(2D);
            //联通区域
            HRegion ConnectedRegions = RegionOpening.Connection();
            //特征提取
            HRegion SelectedRegions = ConnectedRegions.SelectShape("area", "and", 32000, 350000).SelectShape("rectangularity", "and", 0.4, 1).SelectShape("row", "and", 0, 2780);
            //膨胀
            HRegion RegionDilation1 = SelectedRegions.DilationCircle(8D);
            //填充
            HRegion RegionFillUp1 = RegionDilation1.FillUp();
            //合并所有区域为一个整体
            HRegion RegionUnion1 = RegionFillUp1.Union1();
            HRegion ConnectedRegions2 = RegionUnion1.Connection();
            //最小外接旋转矩形
            HRegion RegionTrans2 = ConnectedRegions2.ShapeTrans("rectangle2");
            //通过矩阵数量判断是否存在车牌区域
            int Number = RegionTrans2.CountObj();
            HOperatorSet.GenEmptyObj(out HObject ROI);

            for (int i = 1; i < Number + 1; i++)
            {
                HRegion ObjectSelected = RegionTrans2.SelectObj(i);
                //获取长轴
                double Value1 = ObjectSelected.RegionFeatures("rect2_len1");
                //获取短轴
                double Value2 = ObjectSelected.RegionFeatures("rect2_len2");
                double value = Value1 / Value2;
                if (value > 2.8 && value < 4.3)
                {

                    ROI = ROI.ConcatObj(ObjectSelected);

                }
            }
            //读取ROI的个数
            int Number1 = ROI.CountObj();
            if (Number1 == 1)
            {
                HRegion hRegionROI = new HRegion(ROI);
                //腐蚀
                HRegion RegionErosion = hRegionROI.ErosionRectangle1(80, 80);
                //裁剪
                HImage ImageReduced = ImageMedian.ReduceDomain(RegionErosion);
                HRegion Region1 = ImageReduced.BinaryThreshold("max_separability", "light", out HTuple UsedThreshold1);
                //联通
                HRegion ConnectedRegions1 = Region1.Connection();
                HRegion SelectedRegions1 = ConnectedRegions1.SelectShape("contlength", "and", 105, 150000).SelectShape("area", "and", 500, 100000);
                //膨胀
                HRegion RegionDilation = SelectedRegions1.DilationCircle(8D);
                HRegion RegionUnion = RegionDilation.Union1();
                HRegion ConnectedRegions3 = RegionUnion.Connection();
                //求交集
                HRegion RegionIntersection = ConnectedRegions3.Intersection(SelectedRegions1);
                HRegion SortedRegions = RegionIntersection.SortRegion("character", "true", "row");
                //加载OMC文件
                HOCRMlp mlp = new HOCRMlp();
                mlp.ReadOcrClassMlp("charact.omc");
                //进行OCR识别
                HTuple ocr = mlp.DoOcrMultiClassMlp(SortedRegions, ImageReduced, out HTuple OCRHandle);
                string[] array = ocr.ToSArr();
                //this.textBox1.Text = ocr.ToString();
                hswc2.HalconWindow.SetColor("green");
                hswc2.HalconWindow.ClearWindow();
                this.hswc2.HalconWindow.DispObj(ImageReduced);
                this.hswc2.SetFullImagePart();
                textBox1.Text = null;
                for (int i = 0; i < array.Length; i++)
                {

                    textBox1.Text += ocr[i];
                }
            }
            else
            {
                HRegion hRegionROI1 = new HRegion(ROI);
                HRegion ROI2 = hRegionROI1.SelectShape("area", "and", 110000, 340000);
                HRegion RegionErosion = ROI2.ErosionRectangle1(80, 120);
                HImage ImageReduced = ImageMedian.ReduceDomain(RegionErosion);
                HRegion Region1 = ImageReduced.BinaryThreshold("max_separability", "light", out HTuple UsedThreshold1);
                HRegion ConnectedRegions1 = Region1.Connection();
                HRegion SelectedRegions1 = ConnectedRegions1.SelectShape("contlength", "and", 105, 150000).SelectShape("area", "and", 600, 100000);
                HRegion RegionDilation = SelectedRegions1.DilationCircle(8D);
                HRegion RegionUnion = RegionDilation.Union1();
                HRegion ConnectedRegions3 = RegionUnion.Connection();
                HRegion RegionIntersection = ConnectedRegions3.Intersection(SelectedRegions1);
                HRegion SortedRegions = RegionIntersection.SortRegion("character", "true", "row");
                //加载OMC文件
                HOCRMlp mlp = new HOCRMlp();
                mlp.ReadOcrClassMlp("charact.omc");
                //进行OCR识别
                HTuple ocr = mlp.DoOcrMultiClassMlp(SortedRegions, ImageReduced, out HTuple OCRHandle);
                string[] array = ocr.ToSArr();
                //this.textBox1.Text = ocr.ToString();
                hswc2.HalconWindow.SetColor("green");
                hswc2.HalconWindow.ClearWindow();
                this.hswc2.HalconWindow.DispObj(ImageReduced);
                this.hswc2.SetFullImagePart();
                textBox1.Text = null;
                for (int i = 0; i < array.Length; i++)
                {

                    textBox1.Text += ocr[i];
                }



            }
        }




    }
}

